# Importing Data
INDONESIA <- read_excel("C:/Users/Biniam/Desktop/Documents/Academic/Thesis/Analysis Folder/Excel Files/Oman/Indonesia.xlsx")

# Checking the Imported Data
View(INDONESIA)

# Creating Time Series Data
INDONESIA_ts <- ts(INDONESIA, start=c(2006,01), end=c(2019,01), frequency=12)

# Viewing and Checking the Created Time Series Data
INDONESIA_ts
sum(is.na(INDONESIA_ts))
library(forecast)
INDONESIA_ts <- tsclean(INDONESIA_ts)

# Step – 1 of the Box-Jenkins Methodology (Identification: Plotting the Time Series Data)
plot(INDONESIA_ts)
plot(aggregate(INDONESIA_ts,FUN=mean))

# Decomposing
INDONESIA_ts_decomp <- decompose(INDONESIA_ts)
plot(INDONESIA_ts_decomp)

# Testing for Stationarity
acf(INDONESIA_ts, lag.max=20)
pacf(INDONESIA_ts, lag.max=20)

# To see any seasonal effect
boxplot(INDONESIA_ts~cycle(INDONESIA_ts))

# To remove trend effect
INDONESIA_ts_diff <- diff(INDONESIA_ts)
plot(INDONESIA_ts_diff)

# To remove variance effect
INDONESIA_ts_log <- log(INDONESIA_ts)
plot(INDONESIA_ts_log)

# To remove both (Trend and Variance) effects
INDONESIA_ts_both <- diff(log(INDONESIA_ts))
plot(INDONESIA_ts_both)


# Dealing with ACF and PACF
install.packages("tseries")
library(tseries)
acf(INDONESIA_ts, lag.max=20)
acf(log(INDONESIA_ts), lag.max=20)
acf(diff(INDONESIA_ts), lag.max=20)
acf(diff(log(INDONESIA_ts)), lag.max=20)
pacf(INDONESIA_ts, lag.max=20)
pacf(log(INDONESIA_ts), lag.max=20)
pacf(diff(INDONESIA_ts), lag.max=20)
pacf(diff(log(INDONESIA_ts)), lag.max=20)

# Step-2 of the Box-Jenkins Methodology (Estimating the appropriate model)
INDONESIA_ts_model <- auto.arima(INDONESIA_ts)
INDONESIA_ts_model
INDONESIA_ts_model <- auto.arima(INDONESIA_ts, ic="aic", trace = TRUE)
INDONESIA_ts_model

# Step-3 of the Box-Jenkins Methodology (Diagnosis Checking)
library(tseries)
plot.ts(INDONESIA_ts_model$resid)
acf(INDONESIA_ts_model$residuals, main='ACF Residual')
pacf(INDONESIA_ts_model$residuals, main='ACF Residual')
Box.test(INDONESIA_ts_model$resid, lag=20, type="Ljung-Box")

# Forecasting
options(max.print=1000000)
library(forecast)
INDONESIA_ts_forecast <- forecast (INDONESIA_ts_model, level=c(95), h=263)
plot(INDONESIA_ts_forecast)
INDONESIA_ts_forecast             


write.table(INDONESIA_ts_forecast, file="Indonesia_TSA.csv", sep=",")
